import 'package:flutter/material.dart';
import '../../utils/G.dart';

class Category extends StatefulWidget {
  const Category({Key? key}) : super(key: key);

  @override
  _CategoryState createState() => _CategoryState();
}

class _CategoryState extends State<Category>
    with AutomaticKeepAliveClientMixin {
  List category = [];
  int currentIndex = 0;
  // 2. 声明 wantKeepAlive
  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    // 3. 调用混入中的 build 方法
    super.build(context);

    return FutureBuilder(
        future: G.api.category.list(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            var res = snapshot.data as Map;
            if (res['status'] == 200) {
              category = res['data'];

              return Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Expanded(
                      flex: 2,
                      child: Container(
                          color: Colors.grey.shade100,
                          child: ListView.builder(
                              itemCount: category.length,
                              itemBuilder: (cxt, index) {
                                return _renderCategory(index);
                              }))),
                  Expanded(
                      flex: 5,
                      child: ListView(
                        // shrinkWrap: true,
                        children: [
                          Container(
                              alignment: Alignment.topLeft,
                              padding: const EdgeInsets.all(10.0),
                              child: _renderSubCategory())
                        ],
                      ))
                ],
              );
            } else {
              // 报错
            }
          } else if (snapshot.hasError) {
            return Center(
              child: Text("${snapshot.error}"),
            );
          }

          return G.loader();
        });
  }

  Widget _renderCategory(int i) {
    return GestureDetector(
        child: Container(
            alignment: Alignment.center,
            padding: const EdgeInsets.symmetric(vertical: 15, horizontal: 10),
            decoration: BoxDecoration(
                color: currentIndex == i
                    ? Colors.blue.shade100
                    : Colors.grey.shade100,
                border: Border(
                    right: BorderSide(
                  width: 5,
                  color: currentIndex == i
                      ? Colors.blue.shade200
                      : Colors.grey.shade100,
                ))),
            child: Text(category[i]['cate_name'],
                style: TextStyle(
                    color: currentIndex == i
                        ? Theme.of(context).primaryColor
                        : Colors.black45,
                    fontWeight:
                        currentIndex == i ? FontWeight.w600 : FontWeight.w400,
                    fontSize: 16))),
        onTap: () {
          setState(() {
            currentIndex = i;
          });
        });
  }

  // 展示二级分类
  Widget _renderSubCategory() {
    return Wrap(
      spacing: 10,
      direction: Axis.horizontal,
      alignment: WrapAlignment.start,
      children: List<Widget>.generate(category[currentIndex]['children'].length,
          (int index) {
        return Container(
            padding: const EdgeInsets.fromLTRB(0, 0, 0, 10),
            child: ListTile(
              onTap: () {
                // 跳转到，当前分类下的商品列表
                Map<String, dynamic> p = {
                  'sid': category[currentIndex]['children'][index]['id'],
                  'cate_name': category[currentIndex]['children'][index]
                      ['cate_name']
                };
                print(p);
                //product_list?sid=1&cate_name=新品上市
                G.router.navigateTo(
                    context, '/product_list' + G.parseQuery(params: p));
              },
              leading: G.imageWidget(
                  category[currentIndex]['children'][index]['pic'],
                  width: 30,
                  height: 30),
              title: Text(
                category[currentIndex]['children'][index]['cate_name'],
                style:
                    const TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
                overflow: TextOverflow.ellipsis,
              ),
              trailing:
                  const Icon(Icons.chevron_right, size: 20, color: Colors.grey),
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(10),
                  side: BorderSide(color: Colors.grey.shade400, width: 1)),
            ));
      }).toList(),
    );
  }
}
